#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include<chrono>
#include"cudaService/cudaService.h"
using namespace std;

void getScreen(uchar *RGB32, int w, int h)
{
    // 1.打开设备
    Display *display = XOpenDisplay(NULL);
    if (!display)
    {
        std::cerr << "Error: Unable to open X display." << std::endl;
        return;
    }
    /**
     *  这行代码是用于获取默认屏幕的屏幕编号的操作。让我解释一下它的含义：
    在X Window系统中，可以有多个屏幕（显示器）连接到计算机。
    每个屏幕都有一个唯一的编号，用于区分不同的屏幕。
    通常情况下，如果只有一个屏幕连接到计算机，它将被视为默认屏幕。
    */
    int screen_num = DefaultScreen(display);
    int screen_width = DisplayWidth(display, screen_num);   // 宽度
    int screen_height = DisplayHeight(display, screen_num); // 高度
    // 2.获取RGB32数据
    XImage *x_image = XGetImage(display, RootWindow(display, screen_num),
                                0, 0, screen_width, screen_height, AllPlanes, ZPixmap);
    if (!x_image)
    {
        std::cerr << "Error: Unable to capture screen image." << std::endl;
        return;
    }
    memcpy(RGB32, x_image->data, 4 * w * h);
}
int main(){
    int width = 1920, height = 1080;
    uchar *RGB32 = new uchar[width * height * 4];
    uchar* y = new uchar[width*height];
    uchar* u = new uchar[width*height];
    uchar* v = new uchar[width*height];
    char *yuv444 = new char[width * height * 3];
    char *yuv420 = new char[(int)(width * height * 1.5)];
    auto start = std::chrono::high_resolution_clock::now();
    getScreen(RGB32, width, height);
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    cout << "获取屏幕截图的时间: " << duration.count()<<"\n";
    start = std::chrono::high_resolution_clock::now();
    RGB32ToYUV444Interface((uchar*)RGB32,y,u,v,width,height);
    end = std::chrono::high_resolution_clock::now();
    duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
    cout << "RGB32ToYUV444Interface的时间: " << duration.count()<<"\n";
    FILE* fptr = fopen("screen.yuv444","wb");
    fwrite(y,1,width*height,fptr);
    fwrite(u,1,width*height,fptr);
    fwrite(v,1,width*height,fptr);
    fclose(fptr);
}